package com.market.cart.server.service.impl;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import cn.hutool.core.lang.Snowflake;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.market.cart.server.config.MqConfig;
import com.market.common.core.domain.Result;
import com.market.common.core.exception.GlobalException;
import com.market.common.core.utils.DateUtils;
import com.market.common.core.utils.StringUtils;
import com.market.common.security.service.TokenService;
import com.market.order.common.domain.TOrder;
import com.market.order.common.domain.TOrderDetail;
import com.market.product.common.domain.ProductSkuInfo;
import com.market.product.remote.RemoteProductService;
import com.market.remote.RemoteOrderService;
import com.market.system.common.domain.model.LoginUser;
import nonapi.io.github.classgraph.fileslice.reader.RandomAccessByteBufferReader;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.market.cart.server.mapper.CartInfoMapper;
import com.market.cart.common.domain.CartInfo;
import com.market.cart.server.service.ICartInfoService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 购物车Service业务层处理
 *
 * @author market
 * @date 2024-02-29
 */
@Service
public class CartInfoServiceImpl implements ICartInfoService
{
    private static final String ORDER_TOKEN="order_token";
    private static final String ORDER="order";
    @Autowired
    private CartInfoMapper cartInfoMapper;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private RemoteProductService remoteProductService;
    @Autowired
    private RemoteOrderService remoteOrderService;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;



    /**
     * 查询购物车
     *
     * @param cartInfoId 购物车主键
     * @return 购物车
     */
    @Override
    public CartInfo selectCartInfoByCartInfoId(Integer cartInfoId)
    {
        return cartInfoMapper.selectCartInfoByCartInfoId(cartInfoId);
    }

    /**
     * 查询购物车列表
     *
     * @param cartInfo 购物车
     * @return 购物车
     */
    @Override
    public List<CartInfo> selectCartInfoList(CartInfo cartInfo)
    {
        Long userid = tokenService.getLoginUser().getUserid();
        cartInfo.setUserId(userid);
        return cartInfoMapper.selectCartInfoList(cartInfo);
    }

    /**
     * 新增购物车
     *
     * @param cartInfo 购物车
     * @return 结果
     */
    @Override
    public int insertCartInfo(CartInfo cartInfo)
    {
        cartInfo.setCreateTime(DateUtils.getNowDate());
        LoginUser loginUser = tokenService.getLoginUser();
        //获取用户id
          cartInfo.setUserId(loginUser.getUserid());
        return cartInfoMapper.insertCartInfo(cartInfo);
    }

    /**
     * 修改购物车
     *
     * @param cartInfo 购物车
     * @return 结果
     */
    @Override
    public int updateCartInfo(CartInfo cartInfo)
    {
        return cartInfoMapper.updateCartInfo(cartInfo);
    }

    /**
     * 批量删除购物车
     *
     * @param cartInfoIds 需要删除的购物车主键
     * @return 结果
     */
    @Override
    public int deleteCartInfoByCartInfoIds(Integer[] cartInfoIds)
    {
        return cartInfoMapper.deleteCartInfoByCartInfoIds(cartInfoIds);
    }

    /**
     * 删除购物车信息
     *
     * @param cartInfoId 购物车主键
     * @return 结果
     */
    @Override
    public int deleteCartInfoByCartInfoId(Integer cartInfoId)
    {
        return cartInfoMapper.deleteCartInfoByCartInfoId(cartInfoId);
    }
    /**
     * 结算
     *
     * @param ids 购物车主键,token令牌
     * @return 结果
     */

    @Override
    public Result MultiSettleCart(Integer[] ids,String token) {
        if (ids.length==0){
           throw new GlobalException("订单不能为空");
        }
        //获取用户id
        Long userid = tokenService.getLoginUser().getUserid();
         //将ids数组转为string以逗号拼接
        String idsStr = Arrays.stream(ids)
                .map(Object::toString)
                .collect(Collectors.joining(","));
        //将数据存储在hashmap中,并转为string类型
        HashMap<String, Object> map = new HashMap<>();
        map.put("userid",userid);
        map.put("ids",idsStr);
        String jsonString = JSONObject.toJSONString(map);


         //判断token是否存在,如果redis中有token,则认为是第一次下单,如果没有,则认为重复下单
        //token是这个订单的唯一标识
        //判断和删除写成lua脚本,这里可能会有线程安全问题TODO
        if (token!=null&&redisTemplate.hasKey(token)){
            rabbitTemplate.convertAndSend(MqConfig.ORDER_EXCHANGE,MqConfig.ORDER_ROUTE_KEY,jsonString,
                        message -> {
                            message.getMessageProperties().setMessageId(ORDER+UUID.randomUUID().toString()+new Date().getTime());
                            return message;
                        },new CorrelationData(ORDER+UUID.randomUUID().toString()+new Date().getTime()));
                redisTemplate.delete(token);
                return Result.success(ids,"下單成功請去訂單頁面結算");
        }else {
            return Result.error("下单失败,不能重复下单");
        }

    }


    /**
     * 生成uuid

     * @return 结果
     */
    @Override
    public Result getUUID() {
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            redisTemplate.opsForValue().set( ORDER_TOKEN+uuid,"",3, TimeUnit.MINUTES);
            return Result.success(ORDER_TOKEN+uuid);
    }


}
